package com.car.web.filter;

import com.car.domain.Admin;
import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 简单权限校验过滤器: 没有登录,不允许访问index.jsp
 */
@WebFilter(urlPatterns ="/admin/*")
public class FilterPower implements Filter {
    public void destroy(){
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException{
         //1.登录状态下,可以访问index.jsp
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //2.处理响应中文的乱码问题
        response.setContentType("text/html;charset=utf-8");
        //3.获取session中保存的admin信息
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        //4.从session中获取中用户信息,说明已经登录过了

        if(admin!=null){
            chain.doFilter(request,response);
        }else{
            //5.没有登录不允许访问index.jsp,访问登录页面
            response.sendRedirect("../log/log.jsp");
        }

    }

    public void init(FilterConfig config) throws ServletException{

    }

}
